<?php

class sbAgent {

    public function updateAgentData($data) {
        $agent = tblUsersTable::getInstance()->findByDql('id=?', $data['agent_id'])->getFirst();
        if ($agent) {
            if (!is_null($data['name_en'])) {
                $agent->setTitle($data['name_en']);
            }
            if (!is_null($data['name_he'])) {
                $agent->setTitleHe($data['name_he']);
            }
            if (!is_null($data['name_ru'])) {
                $agent->setTitleRu($data['name_ru']);
            }
            if (!is_null($data['country'])) {
                $c = $this->getCountryIdByName($data['country']);
                $agent->setCountry($c);
            }
            if (!is_null($data['region'])) {
                $r = $this->getRegionIdByName($data['region'], $c);
                $agent->setRegion($r);
            }
            if (!is_null($data['city'])) {
                $ci = $this->getCityIdByName($data['city'], $r, $c);
                $agent->setCity($ci);
            }
            if (!is_null($data['address'])) {
                $agent->setAddress($data['address']);
            }
            if (!is_null($data['time_open'])) {
                if ($data['time_open']['hour'] < 10) {
                    $data['time_open']['hour'] = '0' . $data['time_open']['hour'];
                }
                if ($data['time_open']['minute'] < 10) {
                    $data['time_open']['minute'] = '0' . $data['time_open']['minute'];
                }
                $time = $data['time_open']['hour'] . ':' . $data['time_open']['minute'];
                $agent->setWorkingTimeFrom($time);
            }
            if (!is_null($data['time_close'])) {
                if ($data['time_close']['hour'] < 10) {
                    $data['time_close']['hour'] = '0' . $data['time_close']['hour'];
                }
                if ($data['time_close']['minute'] < 10) {
                    $data['time_close']['minute'] = '0' . $data['time_close']['minute'];
                }
                $time = $data['time_close']['hour'] . ':' . $data['time_close']['minute'];
                $agent->setWorkingTimeTo($time);
            }
            if (!is_null($data['phone1'])) {
                $agent->setPhone1($data['phone1']);
            }
            if (!is_null($data['phone2'])) {
                $agent->setPhone2($data['phone2']);
            }
            if (!is_null($data['fax'])) {
                $agent->setFax($data['fax']);
            }
            if (!is_null($data['email'])) {
                $agent->setEmail($data['email']);
            }
            if (!is_null($data['fax'])) {
                $agent->setFax($data['fax']);
            }
            if (!is_null($data['skype'])) {
                $agent->setScype($data['skype']);
            }
            if (!is_null($data['website'])) {
                $agent->setWebsite($data['website']);
            }
            if (!is_null($data['description_en'])) {
                $agent->setDescriptionEn($data['description_en']);
            }
            if (!is_null($data['description_he'])) {
                $agent->setDescriptionHe($data['description_he']);
            }
            if (!is_null($data['description_ru'])) {
                $agent->setDescriptionRu($data['description_ru']);
            }
            if (!is_null($data['logo'])) {
//                    try {
//                        $binary = base64_decode($image[1]);
//                        $path = sfConfig::get('sf_upload_dir') . '/' . $hotel->getId() . '_' . $i . '.jpg';
//                        $success = file_put_contents($path, $binary);
//
//                        $url = sbValues::URL_LOCALHOST . $hotel->getId() . '_' . $i . '.jpg';
//
//                        $string = $string . $url . ';';
//                    } catch (Exception $e) {
//                        $string = $e;
//                    }
            }

            if (!is_null($data['country']) && !is_null($data['city']) && !is_null($data['address'])) {
                $full = $data['country'] . ' ' . $data['city'] . ' ' . $data['address'];
                $coor = $this->getGeolocationCoordinatos($full);
                if ($coor) {
                    $agent->setLatitude($coor['latitude']);
                    $agent->setLogitude($coor['longitude']);
                }
            }

            $agent->save();
            return true;
        } else {
            return false;
        }
    }

    public function getGeolocationCoordinatos($address) {
        $address = urlencode($address);
        $prepAddr = str_replace(' ', '+', $address);

        $geocode = file_get_contents('http://maps.google.com/maps/api/geocode/json?address=' . $prepAddr . '&sensor=false');

        $output = json_decode($geocode);

        try {
            $lat = $output->results[0]->geometry->location->lat;
            $long = $output->results[0]->geometry->location->lng;

            return array('latitude' => $lat, 'longitude' => $long);
        } catch (Exception $e) {
            return false;
        }
    }

    public function getGeolocationAddress($latitude, $longitude) {
        $url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' . trim($latitude) . ',' . trim($longitude) . '&sensor=false';
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_ENCODING, "");
        $curlData = curl_exec($curl);
        curl_close($curl);
        $data = json_decode($curlData);
        return $data;
    }

    public function parsePossitionAfterGeolocation($possition) {
        if ($possition->status == 'OK') {
            $address = array(
                'country' => $possition->results[5]->address_components[0]->long_name,
                'region' => $possition->results[3]->address_components[0]->long_name,
                'city' => $possition->results[2]->address_components[0]->long_name
            );

            return $address['country'] . ' > ' . $address['region'] . ' > ' . $address['city'];
        } else {
            return 'not found your location.';
        }
    }

    public function foundAgentsByRegions($region, $limit) {
        return Doctrine_Query::create()->
                        select('*')->
                        from('tblUsers')->
                        where('title IS NOT NULL AND reputation IS NOT NULL AND region=?', $region)->
                        orderBy('reputation DESC')->
                        limit($limit)->
                        execute();
    }

    public function foundAgentsByCountry($country, $limit) {
        return Doctrine_Query::create()->
                        select('*')->
                        from('tblUsers')->
                        where('title IS NOT NULL AND reputation IS NOT NULL AND country=?', $country)->
                        orderBy('reputation DESC')->
                        limit($limit)->
                        execute();
    }

    public function foundAgentsByCity($city, $limit) {
        return Doctrine_Query::create()->
                        select('*')->
                        from('tblUsers')->
                        where('title IS NOT NULL AND reputation IS NOT NULL AND city=?', $city)->
                        orderBy('reputation DESC')->
                        limit($limit)->
                        execute();
    }

    public function foundAgentsAround($latitude, $longitude, $limit) {
        $distance = array('small' => 100, 'large' => 1000);
        $tableAgentStirng = array('latitude', 'logitude');
        $distanceQuery = $this->distatnceQuery($latitude, $longitude, $tableAgentStirng[0], $tableAgentStirng[1]);
        $data = $this->requestDistance($distanceQuery, $distance['small'], $limit);
        $result = $data->toArray();
        if (count($result) < $limit) {
            $data = $this->requestDistance($distanceQuery, $distance['large'], $limit);
            $result = $data->toArray();
        }

        return $result;
    }

    public function requestDistance($query, $distance, $limit) {
        return Doctrine_Query::create()->
                        select('*, ' . $query . ' AS distance')->
                        from('tblUsers')->
                        where('status=? AND permissions=? AND reputation IS NOT NULL AND title IS NOT NULL AND latitude IS NOT NULL', array(true, sbValues::PERMISSIONS_AGENT))->
                        having('distance < ' . intval($distance))->
                        orderBy('distance')->
                        limit($limit)->
                        execute();
    }

    public function distatnceQuery($latitude, $longitude, $agentStringLatitude, $agentStringLongitude) {
        return "(((acos(sin((" . $latitude
                . "*pi()/180))*sin((" . $agentStringLatitude
                . "*pi()/180))+cos((" . $latitude . "*pi()/180))*"
                . "cos((" . $agentStringLatitude . "*pi()/180)) * cos((("
                . $longitude . "-" . $agentStringLongitude
                . ")*pi()/180))))*180/pi())*60*1.1515*1.609344)";
    }

    public function veryHighReputation() {
        return Doctrine_Query::create()->
                        select('*')->
                        from('tblUsers')->
                        where('title IS NOT NULL and reputation IS NOT NULL')->
                        orderBy('reputation DESC')->
                        limit(3)->
                        execute();
    }

    public function allCountry() {
        return Doctrine_Core::getTable('tblCountry')->createQuery('a')->execute();
    }

    public function allRegions() {
        return Doctrine_Core::getTable('tblRegion')->createQuery('a')->execute();
    }

    public function allCity() {
        return Doctrine_Core::getTable('tblCity')->createQuery('a')->execute();
    }

    public function sortAgents($country, $region, $city) {
        if ($city != 0) {
            return $this->foundAgentsByCity($city, 30);
        } else if ($city == 0 && $region != 0) {
            return $this->foundAgentsByRegions($region, 30);
        } else if ($city == 0 && $region == 0) {
            return $this->foundAgentsByCountry($country, 30);
        }
    }

    public function sendMailToAgent($data, $agent_id) {
        $name = $data['name'];
        $country = $data['country'];
        $address = $data['address'];
        $email = $data['email'];
        $phone = $data['phone'];
        $message = $message['message'];

        $agent = tblUsersTable::getInstance()->findByDql('id=?', $agent_id)->getFirst();

        $to = $agent->getEmail();
        $subject = 'Бронирование номера';
        $message = '<div><img src="http://azusdex.webcopo.com/travis/web/images/imgLogo.png"/></div>'
                . '<div><h4>Здраствуйте ' . $agent->getFirstName() . ' ' . $agent->getLastName() . '<h4></div>' .
                '<div>С вами желает связатся наш клиент для резервирования гостиничного номера.</div>' .
                '<div><u>Данные клиента:</u></div>' .
                '<div>Name: ' . $name .'</div>'.
                '<div>Country: ' . $country .'</div>'.
                '<div>Address: ' . $address .'</div>'.
                '<div>Phone: ' . $phone .'</div>'.
                '<div>E-mail: ' . $email .'</div>'.
                '<div>Message: ' . $message .'</div>'.
                '<div><p>Спасибо за ваше сотрудничиство с органами власти, может быть мы обработаем текст сообщения!</p></div>';

        $result = sbValues::createNewEmailToAgent($to, $subject, $message);

        return $result;
    }

    public function getCountryIdByName($name) {
        $c = tblCountryTable::getInstance()->findByDql('name_en=?', $name)->getFirst();
        if ($c) {
            return $c->getId();
        } else {
            return $this->createNewCountry($name);
        }
    }

    public function getRegionIdByName($name, $country) {
        $c = tblRegionTable::getInstance()->findByDql('name_en=?', $name)->getFirst();
        if ($c) {
            return $c->getId();
        } else {
            return $this->createNewRegion($name, $country);
        }
    }

    public function getCityIdByName($name, $region, $country) {
        $c = tblCountryTable::getInstance()->findByDql('name_en=?', $name)->getFirst();
        if ($c) {
            return $c->getId();
        } else {
            return $this->createNewCity($name, $region, $country);
        }
    }

    public function createNewCountry($name) {
        $c = new tblCountry();
        $c->setNameEn($name);
        $c->setNameHe($name);
        $c->setNameRu($name);
        $c->setCreateTime(sbValues::getCurrentTime());
        $c->save();
        return $c->getId();
    }

    public function createNewRegion($name, $country) {
        $r = new tblRegion();
        $r->setNameEn($name);
        $r->setNameHe($name);
        $r->setNameRu($name);
        $r->setCountryId($country);
        $r->setCreateTime(sbValues::getCurrentTime());
        $r->save();
        return $r->getId();
    }

    public function createNewCity($name, $region, $country) {
        $c = new tblCity();
        $c->setNameEn($name);
        $c->setNameHe($name);
        $c->setNameRu($name);
        $c->setRegionId($region);
        $c->setCountryId($country);
        $c->setCreateTime(sbValues::getCurrentTime());
        $c->save();
        return $c->getId();
    }

    public function findMapPosition($country, $city, $moked = null) {
        if ($country > 0) {
            $cName = tblCountryTable::getInstance()->findByDql('id=?', $country)->getFirst();
        }

        if ($city > 0) {
            $ccName = tblCityTable::getInstance()->findByDql('id=?', $city)->getFirst();
        }

        if ($cName) {
            $address = $cName->getNameEn();
            if ($ccName) {
                $address = $address + ' ' + $ccName->getNameEn() + ' ' + $moked;
            }
        }

        return $this->getGeolocationCoordinatos($address);
    }

    public function updateAgents() {
        $agents = tblUsersTable::getInstance()->findByDql('permissions=? AND orders IS NULL', sbValues::PERMISSIONS_AGENT);
        foreach ($agents as $a) {
            echo '<div>' . $a->getId() . '---' . $a->getTitle() . '</div>';
            $info = $this->findMapPosition($a->getCountry(), $a->getCity(), $a->getAddress());
            $a->setLatitude($info['latitude']);
            $a->setLogitude($info['longitude']);
            $a->setReputation(0);
            $a->setOrders(0);
            $a->setBalance(0);
            $a->setCommissions(0);
            $a->setCredit(0);
            $a->save();
        }
    }

//                        //get distance
//                        $c = self::getDistance3($customer->getHomeLatitude(), $customer->getHomeLongitude());
//                        //find all users in group in distance < $distance
//                        $g = Doctrine_Query::create()->
//                                select('*, ' . $c . ' AS distance')->
//                                from('tblUser')->
//                                where('active=? and group_id=? and age>?', array(true, $user->getGroupId(), 13))->
//                                having('distance < ' . intval($distance))->
//                                orderBy('distance')->
//                                execute();
}
